#pragma once

#include<iostream>
#include<string>
#include<cstring>
// #include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<functional>
#include<unordered_map>
#include"Log.hpp"



typedef std::function<std::string(const std::string &,const std::string &,uint16_t)> func_t;

Log lg;

enum{
    SOCKET_ERR=1,
    BIND_ERR
};

uint16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";
const int size = 1024;

class UdpServer{
public:
    UdpServer(const uint16_t &port = defaultport, const std::string &ip = defaultip)
    :sockfd_(0),port_(port),ip_(ip),isruning(false){

    }
    
    void Init(){
        //1.创建socket
        sockfd_ = socket(AF_INET,SOCK_DGRAM,0);
        if(sockfd_<0){
            lg(Fatal,"socket, creat error, sockfd:%d",sockfd_);
            exit(SOCKET_ERR);
        }
        lg(Info,"socket create suceess,sockfd:%d",sockfd_);
        // 2.bind socket
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);//转网络字符
        std::cout<<"port_"<<port_<<std::endl;
        local.sin_addr.s_addr = inet_addr(ip_.c_str());//转网络大端
        
        if(bind(sockfd_,(const struct sockaddr *)&local, sizeof(local))<0){
            lg(Fatal,"bind  error, errno: %d,err stirng: %s",errno,strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info,"bind success,errno: %d,err string: %s",errno,strerror(errno));
    }
    
    void CheckUser(const struct sockaddr_in &client, const std::string clientip, uint16_t clientport){
        auto iter = online_user_.find(clientip);
        if(iter == online_user_.end()){
            online_user_.insert({clientip,client});
            std::cout<<"["<<clientip<<":"<<clientport<<"] add to online user."<<std::endl;
        }
    }
    
    void Broadcast(const std::string &info, const std::string clientip,uint16_t clientport){ // 广播给所有的user
        for(const auto &user:online_user_){
            std::string message = "[";
            message += clientip;
            message += ":";
            message +=std::to_string(clientport);
            message +="]# ";
            message +=info;
            socklen_t len = sizeof(user.second);
           
            sendto(sockfd_,message.c_str(),message.size(),0,(struct sockaddr*)(&user.second),len);
        }
    }

    void Run(){
        isruning = true;
        char inbuffer[size];
        while(isruning){
            std::cout<<"run "<<std::endl;
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_,inbuffer,sizeof(inbuffer)-1,0,(struct sockaddr*)&client, &len);
            if(n<0){
                lg(Warning,"recvfrom error, errno: %d,err string: %s",errno, strerror(errno));
                continue;
            }
            inbuffer[n]=0;//控制inbuffer大小，否则大小为1024
            uint16_t clientport = ntohs(client.sin_port);
            std::string clientip = inet_ntoa(client.sin_addr);//inet_ntoa 网络大端转主机大/小端
            CheckUser(client,clientip,clientport);
            std::string info = inbuffer;

            Broadcast(info,clientip,clientport);//使用了Log.hpp中的Info=0;
        }
    }
    
    ~UdpServer(){
        if(sockfd_>0) close(sockfd_);
    }

private:
    int sockfd_;
    std::string ip_;
    uint16_t port_;
    bool isruning;
    std::unordered_map<std::string, struct sockaddr_in> online_user_;    
};








